<template>
    <div class="order-management">
        <!-- 页面标题 -->
        <div class="page-header">
            <h2 class="page-title">订单管理</h2>
        </div>

        <!-- 搜索与操作栏 -->
        <div class="operation-bar">
            <div class="search-box">
                <el-input
                        v-model="searchKeyword"
                        placeholder="搜索订单ID/用户ID"
                        prefix-icon="Search"
                        class="search-input"
                        @keyup.enter="handleSearch"
                />
                <el-button type="primary" @click="handleSearch">搜索</el-button>
            </div>
        </div>

        <!-- 订单列表表格 -->
        <div class="order-table-container">
            <el-table
                    :data="orderList"
                    border
                    stripe
                    style="width: 100%"
                    :empty-text="loading ? '加载中...' : '暂无订单数据'"
                    :loading="loading"
            >
                <!-- 订单ID -->
                <el-table-column
                        prop="orderId"
                        label="订单ID"
                        width="140"
                        align="center"
                />
                <!-- 用户ID -->
                <el-table-column
                        prop="userId"
                        label="用户ID"
                        width="140"
                        align="center"
                />
                <!-- 商品ID -->
                <el-table-column
                        prop="productId"
                        label="商品ID"
                        width="140"
                        align="center"
                />
                <!-- 地址ID -->
                <el-table-column
                        prop="addressId"
                        label="地址ID"
                        width="140"
                        align="center"
                />
                <!-- 订单状态（可直接下拉修改） -->
                <el-table-column
                        prop="status"
                        label="订单状态"
                        width="180"
                        align="center"
                >
                    <template #default="scope">
                        <el-select
                                v-model="scope.row.status"
                                placeholder="选择状态"
                                @change="handleStatusChange(scope.row)"
                                size="small"
                                style="width: 120px"
                        >
                            <el-option
                                    v-for="item in statusOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                            />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="price"
                    label="金额"
                    width="140"
                    align="center"
                >
                </el-table-column>
                <el-table-column
                        prop="createdAt"
                        label="创建时间"
                        width="200"
                        align="center"
                >
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页控件 -->
        <div class="pagination-container">
            <el-pagination
                    @current-change="jump"
                    :current-page="pages.page"
                    :page-size="pages.limit"
                    :total="totalCount"
                    layout="prev, pager, next, ->, jumper, total"
                    class="pagination"
            />
        </div>
    </div>
</template>

<script setup>
import axios from "@/utils/axios.js";
import { onMounted, reactive, ref } from "vue";
// 1. 补充Element Plus组件同步导入（避免ElMessage等未定义报错）
import {
    ElMessage,
    ElTable,
    ElTableColumn,
    ElInput,
    ElButton,
    ElPagination,
    ElSelect,
    ElOption
} from "element-plus";

// 分页参数
const pages = reactive({
    page: 1,
    limit: 6,
});

// 搜索关键词
const searchKeyword = ref("");
// 订单总条数（从接口获取）
const totalCount = ref(0);
// 加载状态
const loading = ref(false);
// 订单列表数据
const orderList = ref([
    {
        orderId: 0,
        userId: 0,
        productId: 0,
        addressId: "",
        status: "",
        createdAt: "",
        price: 0,
    },
]);

// 订单状态选项（根据实际业务调整value和label）
const statusOptions = ref([
    { value: "pending", label: "待付款" },
    { value: "paid", label: "已付款" },
    { value: "shipped", label: "已发货" },
    { value: "completed", label: "已完成" },
    { value: "cancelled", label: "已取消" },
]);

// 页面挂载时加载订单数据
onMounted(() => {
    init();
});

// 初始化加载订单列表
const init = () => {
    loading.value = true;
    axios
        .get(`/api/ordersPage?page=${pages.page}&limit=${pages.limit}`)
        .then((res) => {
            console.log("订单列表数据：", res.data);
            orderList.value = res.data.records || res.data;
            console.log("订单列表数据：", res.data);
            console.log("金额"+res.data.price)
            totalCount.value = res.data.total || orderList.value.length;
        })
        .catch((err) => {
            console.error("加载订单失败：", err);
            ElMessage.error("加载订单失败，请重试");
            orderList.value = [];
            totalCount.value = 0;
        })
        .finally(() => {
            loading.value = false;
        });
};

// 搜索订单
const handleSearch = () => {
    if (!searchKeyword.value.trim()) {
        ElMessage.info("请输入搜索关键词（订单ID/用户ID）");
        return;
    }
    ElMessage({
        message: "功能炒鸡开发中..",
        type: "info",
        duration: 1500,
    });
};

// 下拉框修改订单状态
const handleStatusChange = (row) => {
    axios
        .post("/api/updateOrderStatus", {
            orderId: row.orderId,
            status: row.status,
        })
        .then((res) => {
            if (res.code === 200) {
                ElMessage({
                    message: "订单状态更新成功",
                    type: "success",
                    duration: 1500,
                });
            } else {
                ElMessage.error(res.msg || "订单状态更新失败");
                init();
            }
        })
        .catch((err) => {
            console.error("更新订单状态失败：", err);
            ElMessage.error("更新订单状态失败，请重试");
            init();
        });
};

// 分页跳转
const jump = (val) => {
    pages.page = val;
    init();
};

// 2. 新增：时间格式化工具函数（处理后端返回的时间数据）
const formatTime = (time) => {
    // 情况1：如果时间为空/undefined，显示“--”
    if (!time) return "--";

    // 情况2：如果是时间戳（数字），先转为Date对象
    const date = typeof time === "number" ? new Date(time) : new Date(time);

    // 情况3：如果时间格式无效，显示“无效时间”
    if (isNaN(date.getTime())) return "无效时间";

    // 格式化：年-月-日 时:分:秒（根据需求调整格式）
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，补0
    const day = String(date.getDate()).padStart(2, "0");
    const hour = String(date.getHours()).padStart(2, "0");
    const minute = String(date.getMinutes()).padStart(2, "0");
    const second = String(date.getSeconds()).padStart(2, "0");

    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};
</script>

<style scoped>
/* 原有样式不变 */
.order-management {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: 100vh;
}
.page-header {
    margin-bottom: 24px;
}
.page-title {
    font-size: 20px;
    font-weight: 600;
    color: #333;
}
.operation-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 12px;
    flex-wrap: wrap;
}
.search-box {
    display: flex;
    align-items: center;
    gap: 10px;
}
.search-input {
    width: 300px;
}
.order-table-container {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    margin-bottom: 24px;
    overflow: hidden;
}
.pagination-container {
    display: flex;
    justify-content: center;
    padding: 10px 0;
}
.pagination {
    --el-pagination-font-size: 14px;
}
@media (max-width: 768px) {
    .operation-bar {
        flex-direction: column;
        align-items: flex-start;
    }
    .search-input {
        width: 100%;
    }
    .order-table-container {
        overflow-x: auto;
    }
}
</style>